
// @ts-nocheck

export const ifrmaPostMessageFnify = ({ fn, timeout = 3000 }: { fn: string; timeout?: number }) => {
    return async (..._args: any[]) => {
      // eslint-disable-next-line prefer-destructuring
      const iframe: HTMLIFrameElement = _args[0];
      const args = _args.slice(1);
  
      if (!iframe || !iframe.contentWindow) {
        throw new Error('error, iframe 必传参数！');
      }
  
      // // eslint-disable-next-line prefer-destructuring
      // const contentWindow = iframe.contentWindow;
      const topWindow = window;
  
      const uid = Math.random().toString(16);
  
      let _resolve;
      let _reject;
  
      const promise = new Promise((resolve, reject) => {
        _resolve = resolve;
        _reject = reject;
      });
  
      // let isCalling = false;
      let isCalled = false;
      let timeId;
  
      const listen = (e: MessageEvent<any>) => {
        if (e.data.uid !== uid) {
          return;
        }
  
        const { type } = e.data;
  
        if (type === 'fn-call-start') {
          if (timeId) {
            clearTimeout(timeId);
            timeId = null;
          }
          // isCalling = true;
          // console.log('异步函数开始调用成功', fn);
        }
  
        if (type === 'fn-ret') {
          if (timeId) {
            clearTimeout(timeId);
            timeId = null;
          }
          // isCalling = false;
          isCalled = true;
          topWindow.removeEventListener('message', listen);
  
          if (e.data.error) {
            console.log(e.data.error);
            return _reject(`call ${fn} error: ${e.data.error.message}`);
          }
          return _resolve(e.data.result);
        }
      };
  
      topWindow.addEventListener('message', listen);
  
      timeId = setTimeout(() => {
        if (isCalled) {
          timeId = null;
          return;
        }
        topWindow.removeEventListener('message', listen);
        _reject(new Error(`函数 ${fn}: 调用超时,超时配置: ${timeout}`));
      }, timeout);
  
      iframe.contentWindow.postMessage(
        {
          type: 'fn-call',
          iframeName: iframe.name,
          uid,
          fn,
          args,
        },
        '*'
      );
  
      return promise;
    };
  };
  